<!DOCTYPE html>






<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="tensorflow,python,linux,vmware,ubuntu," />










<meta name="description" content="相关链接 Tensorflow笔记  开发环境 在windows安装Anaconda以后切换版本python 3.5以后安装tensorflow一直失败,宝宝也是很委屈..以下详细操作步骤可以看上边链接得视频哦   下载VMware、Ubuntu安装 安装python 2.7、pip  12sudo apt install pythonsudo apt install python-pip  安装">
<meta name="keywords" content="tensorflow,python,linux,vmware,ubuntu">
<meta property="og:type" content="article">
<meta property="og:title" content="tensorflow-learning">
<meta property="og:url" content="https://zhangyuhan2016.gitee.io/2018/08/03/tensorflow-learning/index.html">
<meta property="og:site_name" content="zhangyuhan2016">
<meta property="og:description" content="相关链接 Tensorflow笔记  开发环境 在windows安装Anaconda以后切换版本python 3.5以后安装tensorflow一直失败,宝宝也是很委屈..以下详细操作步骤可以看上边链接得视频哦   下载VMware、Ubuntu安装 安装python 2.7、pip  12sudo apt install pythonsudo apt install python-pip  安装">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-08-07T09:40:21.376Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="tensorflow-learning">
<meta name="twitter:description" content="相关链接 Tensorflow笔记  开发环境 在windows安装Anaconda以后切换版本python 3.5以后安装tensorflow一直失败,宝宝也是很委屈..以下详细操作步骤可以看上边链接得视频哦   下载VMware、Ubuntu安装 安装python 2.7、pip  12sudo apt install pythonsudo apt install python-pip  安装">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhangyuhan2016.gitee.io/2018/08/03/tensorflow-learning/"/>





  <title>tensorflow-learning | zhangyuhan2016</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<header style="position: fixed;z-index: 99999999;background-color: #eee;width: 100%;text-align: center;">
    <h3>感谢您的关注，最新博客已迁移至 <mark style="background-color: #07c160;padding: 4px;"><a style="color: #fff;" href="https://blog.hi-zhang.com" target="_blank">blog.hi-zhang.com</a></mark> </h3>
</header>






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhangyuhan2016</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <p class="site-subtitle"></p>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />

            归档
          </a>
        </li>



    </ul>



</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhangyuhan2016.gitee.io/2018/08/03/tensorflow-learning/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhangyuhan2016">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/18086072?s=460&v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhangyuhan2016">
    </span>


      <header class="post-header">



          <h1 class="post-title" itemprop="name headline">tensorflow-learning</h1>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-03T11:25:47+08:00">
                2018-08-03
              </time>



              <span class="post-meta-divider">|</span>



              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>

                <span class="post-meta-item-text">更新于&#58;</span>

              <time title="更新于" itemprop="dateModified" datetime="2018-08-07T17:40:21+08:00">
                2018-08-07
              </time>

          </span>





              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/03/tensorflow-learning/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/08/03/tensorflow-learning/" itemprop="commentCount"></span>
                </a>
              </span>





             <span id="/2018/08/03/tensorflow-learning/" class="leancloud_visitors" data-flag-title="tensorflow-learning">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>

                 <span class="post-meta-item-text">阅读次数&#58;</span>

                 <span class="leancloud-visitors-count"></span>
             </span>





            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,181
                </span>



                <span class="post-meta-divider">|</span>



                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                  <span class="post-meta-item-text">阅读时长 &asymp;</span>

                <span title="阅读时长">
                  7
                </span>

            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <h2 id="相关链接"><a href="#相关链接" class="headerlink" title="相关链接"></a>相关链接</h2><ul>
<li><a href="https://www.icourse163.org/learn/PKU-1002536002?tid=1002700003#/learn/announce" target="_blank" rel="noopener">Tensorflow笔记</a></li>
</ul>
<h2 id="开发环境"><a href="#开发环境" class="headerlink" title="开发环境"></a>开发环境</h2><blockquote>
<p>在windows安装Anaconda以后切换版本python 3.5以后安装tensorflow一直失败,宝宝也是很委屈..<br>以下详细操作步骤可以看上边链接得视频哦</p>
</blockquote>
<ol>
<li>下载VMware、Ubuntu安装</li>
<li><p>安装python 2.7、pip</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sudo apt install python</span><br><span class="line">sudo apt install python-pip</span><br></pre></td></tr></table></figure>
</li>
<li><p>安装tensorflow</p>
<ul>
<li><a href="https://mirrors.tuna.tsinghua.edu.cn/help/tensorflow" target="_blank" rel="noopener">TensorFlow 镜像</a></li>
</ul>
</li>
<li><p>检查</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; python</span><br><span class="line">&gt;&gt;&gt; import tensorflow as tf</span><br><span class="line">&gt;&gt;&gt; tf.__version__</span><br></pre></td></tr></table></figure>
</li>
</ol>
<a id="more"></a>
<h3 id="VMware相关"><a href="#VMware相关" class="headerlink" title="VMware相关"></a>VMware相关</h3><ol>
<li>打开虚拟机</li>
<li>菜单&gt; 虚拟机 &gt; 安装VMware-Tools</li>
<li>点击桌面出现得光驱</li>
<li><p>复制其中的.tar.gz文件到其他文件夹,解压</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tar zxpf xxxx.tar.gz</span><br></pre></td></tr></table></figure>
</li>
<li><p>进入解压后的文件夹</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo ./vmware-install.pl</span><br></pre></td></tr></table></figure>
</li>
<li><p>一路回车默认选择后成功安装</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-- the VMware team</span><br></pre></td></tr></table></figure>
</li>
<li><p>菜单&gt; 查看 &gt; 自动调整大小</p>
</li>
</ol>
<h2 id="mnist-数字识别"><a href="#mnist-数字识别" class="headerlink" title="mnist 数字识别"></a>mnist 数字识别</h2><ol>
<li>下载<a href="http://yann.lecun.com/exdb/mnist/" target="_blank" rel="noopener">mnist</a>放入<strong>data</strong>文件夹</li>
<li><p>安装PIL</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install -i https://pypi.douban.com/simple pillow</span><br></pre></td></tr></table></figure>
</li>
<li><p>写代码</p>
</li>
</ol>
<h3 id="前向传播"><a href="#前向传播" class="headerlink" title="前向传播"></a><strong>前向传播</strong></h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#coding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="comment"># 定义输入 &amp; 输出 &amp; 隐藏层</span></span><br><span class="line">InNode = <span class="number">784</span></span><br><span class="line">OutNode = <span class="number">10</span></span><br><span class="line">LayNode = <span class="number">500</span></span><br><span class="line"><span class="comment"># regularizer 正则化</span></span><br><span class="line"><span class="comment"># 随机生成w</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_weight</span><span class="params">(shape,regularizer)</span>:</span></span><br><span class="line">    w = tf.Variable(tf.truncated_normal(shape,stddev=<span class="number">0.1</span>))</span><br><span class="line">    <span class="keyword">if</span> regularizer != <span class="keyword">None</span>: tf.add_to_collection(<span class="string">'losses'</span>,tf.contrib.layers.l2_regularizer(regularizer)(w))</span><br><span class="line">    <span class="keyword">return</span> w</span><br><span class="line"><span class="comment"># get</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_bias</span><span class="params">(shape)</span>:</span></span><br><span class="line">    b = tf.Variable(tf.zeros(shape))</span><br><span class="line">    <span class="keyword">return</span> b</span><br><span class="line"><span class="comment"># 搭建神经元网络</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(x,regularizer)</span>:</span></span><br><span class="line">    w1 = get_weight([InNode,LayNode],regularizer)</span><br><span class="line">    b1 = get_bias([LayNode])</span><br><span class="line">    y1 = tf.nn.relu(tf.matmul(x,w1) + b1)</span><br><span class="line"></span><br><span class="line">    w2 = get_weight([LayNode,OutNode],regularizer)</span><br><span class="line">    b2 = get_bias([OutNode])</span><br><span class="line">    y2 = tf.matmul(y1,w2) + b2</span><br><span class="line">    <span class="keyword">return</span> y2</span><br></pre></td></tr></table></figure>
<h3 id="反向传播"><a href="#反向传播" class="headerlink" title="反向传播"></a><strong>反向传播</strong></h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#coding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">from</span> tensorflow.examples.tutorials.mnist <span class="keyword">import</span> input_data</span><br><span class="line"><span class="keyword">import</span> mnist_forward</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输入量，学习率，衰减率，正则化系数，总轮数，滑动衰减，保存路径，保存名</span></span><br><span class="line">BatchSize = <span class="number">200</span></span><br><span class="line">LearningBase = <span class="number">0.1</span></span><br><span class="line">LearningDecay = <span class="number">0.99</span></span><br><span class="line">Regularizer = <span class="number">0.0001</span></span><br><span class="line">Steps = <span class="number">50000</span></span><br><span class="line">MovingDecay = <span class="number">0.99</span></span><br><span class="line">ModelPath = <span class="string">'./model/'</span></span><br><span class="line">ModelName = <span class="string">'mnist_model'</span></span><br><span class="line"><span class="comment"># 反向</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">backward</span><span class="params">(mnist)</span>:</span></span><br><span class="line">    x = tf.placeholder(tf.float32,[<span class="keyword">None</span>, mnist_forward.InNode])</span><br><span class="line">    y_ = tf.placeholder(tf.float32,[<span class="keyword">None</span>, mnist_forward.OutNode])</span><br><span class="line">    y = mnist_forward.forward(x,Regularizer)</span><br><span class="line">    global_step = tf.Variable(<span class="number">0</span>,trainable=<span class="keyword">False</span>)</span><br><span class="line"></span><br><span class="line">    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,<span class="number">1</span>))</span><br><span class="line">    cem = tf.reduce_mean(ce)</span><br><span class="line">    loss = cem + tf.add_n(tf.get_collection(<span class="string">'losses'</span>))</span><br><span class="line"></span><br><span class="line">    learningRate = tf.train.exponential_decay(</span><br><span class="line">        LearningBase,</span><br><span class="line">        global_step,</span><br><span class="line">        mnist.train.num_examples / BatchSize,</span><br><span class="line">        LearningDecay,</span><br><span class="line">        staircase=<span class="keyword">True</span></span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    train_step = tf.train.GradientDescentOptimizer(learningRate).minimize(loss,global_step=global_step)</span><br><span class="line">    ema = tf.train.ExponentialMovingAverage(MovingDecay,global_step)</span><br><span class="line">    ema_op = ema.apply(tf.trainable_variables())</span><br><span class="line">    <span class="keyword">with</span> tf.control_dependencies([train_step,ema_op]):</span><br><span class="line">        train_op = tf.no_op(name=<span class="string">'train'</span>)</span><br><span class="line">    </span><br><span class="line">    saver = tf.train.Saver()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">        init_op = tf.global_variables_initializer()</span><br><span class="line">        sess.run(init_op)</span><br><span class="line">        <span class="comment"># 断点续训</span></span><br><span class="line">        ckpt = tf.train.get_checkpoint_state(ModelPath)</span><br><span class="line">        <span class="keyword">if</span> ckpt <span class="keyword">and</span> ckpt.model_checkpoint_path:</span><br><span class="line">            saver.restore(sess,ckpt.model_checkpoint_path)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> range(Steps):</span><br><span class="line">            xs, ys = mnist.train.next_batch(BatchSize)</span><br><span class="line">            _, loss_value, step = sess.run([train_op,loss,global_step],feed_dict=&#123;x: xs,y_:ys&#125;)</span><br><span class="line">            <span class="keyword">if</span> i % <span class="number">1000</span> == <span class="number">0</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">"%d steps,loss: %g"</span> %(step,loss_value)</span><br><span class="line">                saver.save(sess,os.path.join(ModelPath,ModelName),global_step=global_step)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    mnist = input_data.read_data_sets(<span class="string">'./data/'</span>,one_hot=<span class="keyword">True</span>)</span><br><span class="line">    backward(mnist)</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h3 id="测试"><a href="#测试" class="headerlink" title="测试"></a><strong>测试</strong></h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#coding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">from</span> tensorflow.examples.tutorials.mnist <span class="keyword">import</span> input_data</span><br><span class="line"><span class="keyword">import</span> mnist_forward</span><br><span class="line"><span class="keyword">import</span> mnist_backward</span><br><span class="line">TestSecs = <span class="number">5</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 测试</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test</span><span class="params">(mnist)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> tf.Graph().as_default() <span class="keyword">as</span> g:</span><br><span class="line">        <span class="comment"># 定义x,y</span></span><br><span class="line">        x = tf.placeholder(tf.float32,[<span class="keyword">None</span>,mnist_forward.InNode])</span><br><span class="line">        y_ = tf.placeholder(tf.float32,[<span class="keyword">None</span>,mnist_forward.OutNode])</span><br><span class="line">        y = mnist_forward.forward(x,<span class="keyword">None</span>)</span><br><span class="line"></span><br><span class="line">        ema = tf.train.ExponentialMovingAverage(mnist_backward.MovingDecay)</span><br><span class="line">        ema_restore = ema.variables_to_restore()</span><br><span class="line">        <span class="comment"># 实例化saver</span></span><br><span class="line">        saver = tf.train.Saver(ema_restore)</span><br><span class="line">        <span class="comment"># 计算正确率</span></span><br><span class="line">        correct_prediction = tf.equal(tf.argmax(y,<span class="number">1</span>),tf.argmax(y_,<span class="number">1</span>))</span><br><span class="line">        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">            <span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">                <span class="comment"># 加载模型</span></span><br><span class="line">                ckpt = tf.train.get_checkpoint_state(mnist_backward.ModelPath)</span><br><span class="line">                <span class="keyword">if</span> ckpt <span class="keyword">and</span> ckpt.model_checkpoint_path:</span><br><span class="line">                    saver.restore(sess,ckpt.model_checkpoint_path)</span><br><span class="line">                    global_step = ckpt.model_checkpoint_path.split(<span class="string">"/"</span>)[<span class="number">-1</span>].split(<span class="string">"-"</span>)[<span class="number">-1</span>]</span><br><span class="line">                    tempDict = &#123;</span><br><span class="line">                        x: mnist.test.images,</span><br><span class="line">                        y_: mnist.test.labels</span><br><span class="line">                    &#125;</span><br><span class="line">                    accuracy_score = sess.run(accuracy,feed_dict=tempDict)</span><br><span class="line">                    <span class="keyword">print</span> <span class="string">"%s steps,acc: %g"</span> %(global_step,accuracy_score)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    <span class="keyword">print</span>  <span class="string">"not ckpt"</span></span><br><span class="line">                    <span class="keyword">return</span></span><br><span class="line">            time.sleep(TestSecs)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    mnist = input_data.read_data_sets(<span class="string">'./data/'</span>,one_hot=<span class="keyword">True</span>)</span><br><span class="line">    test(mnist)</span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h3 id="图片识别"><a href="#图片识别" class="headerlink" title="图片识别"></a><strong>图片识别</strong></h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#coding=utf-8</span></span><br><span class="line"><span class="keyword">import</span> tensorflow <span class="keyword">as</span> tf</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image</span><br><span class="line"><span class="keyword">import</span> mnist_backward</span><br><span class="line"><span class="keyword">import</span> mnist_forward</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">restore_model</span><span class="params">(testPicArr)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> tf.Graph().as_default() <span class="keyword">as</span> tg:</span><br><span class="line">        x = tf.placeholder(tf.float32,[<span class="keyword">None</span>,mnist_forward.InNode])</span><br><span class="line">        y = mnist_forward.forward(x,<span class="keyword">None</span>)</span><br><span class="line">        preValue = tf.argmax(y,<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">        variable_averages = tf.train.ExponentialMovingAverage(mnist_backward.MovingDecay)</span><br><span class="line">        variable_restore = variable_averages.variables_to_restore()</span><br><span class="line">        saver = tf.train.Saver(variable_restore)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">with</span> tf.Session() <span class="keyword">as</span> sess:</span><br><span class="line">            <span class="comment"># 断点续训</span></span><br><span class="line">            ckpt = tf.train.get_checkpoint_state(mnist_backward.ModelPath)</span><br><span class="line">            <span class="keyword">if</span> ckpt <span class="keyword">and</span> ckpt.model_checkpoint_path:</span><br><span class="line">                saver.restore(sess,ckpt.model_checkpoint_path)</span><br><span class="line">                preValue = sess.run(preValue,feed_dict=&#123;x: testPicArr&#125;)</span><br><span class="line">                <span class="keyword">return</span> preValue</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">print</span> <span class="string">"not ckpt !"</span></span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>    </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pre_pic</span><span class="params">(picName)</span>:</span></span><br><span class="line">    img = Image.open(picName)</span><br><span class="line">    reIm = img.resize((<span class="number">28</span>,<span class="number">28</span>),Image.ANTIALIAS)</span><br><span class="line">    im_arr = np.array(reIm.convert(<span class="string">'L'</span>))</span><br><span class="line">    threshold = <span class="number">50</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">28</span>):</span><br><span class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">28</span>):</span><br><span class="line">            im_arr[i][j] = <span class="number">255</span> - im_arr[i][j]</span><br><span class="line">            <span class="keyword">if</span>(im_arr[i][j] &lt; threshold):</span><br><span class="line">                im_arr[i][j] = <span class="number">0</span></span><br><span class="line">            <span class="keyword">else</span>: im_arr[i][j] = <span class="number">255</span></span><br><span class="line">    </span><br><span class="line">    nm_arr = im_arr.reshape([<span class="number">1</span>,<span class="number">784</span>])</span><br><span class="line">    nm_arr = nm_arr.astype(np.float32)</span><br><span class="line">    img_ready = np.multiply(nm_arr,<span class="number">1.0</span>/<span class="number">255.0</span>)</span><br><span class="line">    <span class="keyword">return</span> img_ready</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">application</span><span class="params">()</span>:</span></span><br><span class="line">    testPic = raw_input(<span class="string">"img of :"</span>)</span><br><span class="line">    testPicArr = pre_pic(testPic)</span><br><span class="line">    preValue = restore_model(testPicArr)</span><br><span class="line">    <span class="keyword">print</span> <span class="string">"the number is:"</span>,preValue</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    application()</span><br><span class="line"><span class="keyword">if</span> __name__  == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h2 id="待续"><a href="#待续" class="headerlink" title="待续"></a>待续</h2>

    </div>







      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">




      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/zfb.png" alt="zhangyuhan2016 支付宝"/>
        <p>支付宝</p>
      </div>




  </div>
</div>

      </div>




    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/tensorflow/" rel="tag">tensorflow</a>

            <a href="/tags/python/" rel="tag">python</a>

            <a href="/tags/linux/" rel="tag">linux</a>

            <a href="/tags/vmware/" rel="tag">vmware</a>

            <a href="/tags/ubuntu/" rel="tag">ubuntu</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2018/04/26/vue-cli-3-0/" rel="next" title="vue@cli-3.0">
                <i class="fa fa-chevron-left"></i> vue@cli-3.0
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2018/08/20/git-note/" rel="prev" title="git常见问题">
                git常见问题 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>






    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>





        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image"
                src="https://avatars3.githubusercontent.com/u/18086072?s=460&v=4"
                alt="zhangyuhan2016" />

              <p class="site-author-name" itemprop="name">zhangyuhan2016</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives/">

                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zhangyuhan2016" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>


          </div>








        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#相关链接"><span class="nav-number">1.</span> <span class="nav-text"><a href="#&#x76F8;&#x5173;&#x94FE;&#x63A5;" class="headerlink" title="&#x76F8;&#x5173;&#x94FE;&#x63A5;"></a>&#x76F8;&#x5173;&#x94FE;&#x63A5;</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发环境"><span class="nav-number">2.</span> <span class="nav-text"><a href="#&#x5F00;&#x53D1;&#x73AF;&#x5883;" class="headerlink" title="&#x5F00;&#x53D1;&#x73AF;&#x5883;"></a>&#x5F00;&#x53D1;&#x73AF;&#x5883;</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#VMware相关"><span class="nav-number">2.1.</span> <span class="nav-text"><a href="#VMware&#x76F8;&#x5173;" class="headerlink" title="VMware&#x76F8;&#x5173;"></a>VMware&#x76F8;&#x5173;</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#mnist-数字识别"><span class="nav-number">3.</span> <span class="nav-text"><a href="#mnist-&#x6570;&#x5B57;&#x8BC6;&#x522B;" class="headerlink" title="mnist &#x6570;&#x5B57;&#x8BC6;&#x522B;"></a>mnist &#x6570;&#x5B57;&#x8BC6;&#x522B;</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#前向传播"><span class="nav-number">3.1.</span> <span class="nav-text"><a href="#&#x524D;&#x5411;&#x4F20;&#x64AD;" class="headerlink" title="&#x524D;&#x5411;&#x4F20;&#x64AD;"></a><strong>&#x524D;&#x5411;&#x4F20;&#x64AD;</strong></span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反向传播"><span class="nav-number">3.2.</span> <span class="nav-text"><a href="#&#x53CD;&#x5411;&#x4F20;&#x64AD;" class="headerlink" title="&#x53CD;&#x5411;&#x4F20;&#x64AD;"></a><strong>&#x53CD;&#x5411;&#x4F20;&#x64AD;</strong></span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#测试"><span class="nav-number">3.3.</span> <span class="nav-text"><a href="#&#x6D4B;&#x8BD5;" class="headerlink" title="&#x6D4B;&#x8BD5;"></a><strong>&#x6D4B;&#x8BD5;</strong></span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#图片识别"><span class="nav-number">3.4.</span> <span class="nav-text"><a href="#&#x56FE;&#x7247;&#x8BC6;&#x522B;" class="headerlink" title="&#x56FE;&#x7247;&#x8BC6;&#x522B;"></a><strong>&#x56FE;&#x7247;&#x8BC6;&#x522B;</strong></span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#待续"><span class="nav-number">4.</span> <span class="nav-text"><a href="#&#x5F85;&#x7EED;" class="headerlink" title="&#x5F85;&#x7EED;"></a>&#x5F85;&#x7EED;</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
    <div class="post-block page my-thanks">
        <div class="my-title">致谢</div>
        <div class="thanks">Hexo</div>
        <div class="thanks">Next & Gemini</div>
        <div class="thanks">Gitee</div>
    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">









      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>



























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>




    <script type="text/javascript" src="/lib/three/three.min.js"></script>




    <script type="text/javascript" src="/lib/three/canvas_lines.min.js"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>




  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>









      <script id="dsq-count-scr" src="https://.disqus.com/count.js" async></script>



      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://zhangyuhan2016.gitee.io/2018/08/03/tensorflow-learning/';
          this.page.identifier = '2018/08/03/tensorflow-learning/';
          this.page.title = 'tensorflow-learning';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>






























  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>

  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'xxTmc7jwpAd2bWhmkKOI7IGY-gzGzoHsz',
        appKey: 'glPUiD8ljbJsKYhBg5E0ghII',
        placeholder: '说点什么呗 ヾﾉ≧∀≦)o',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>












  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("mpOMyFHLi7a5S0ka5mv3cz7C-gzGzoHsz", "3t0W0au9Mxf0lOGFDF8u89pc");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>
















</body>
</html>
